<template>
  <div>
    <n-card :bordered="false" class="fromCard">
      <BasicForm
        @register="register"
        :Toption="dealStatus"
        @submit="handleSubmit"
        @reset="handleReset"
      >
        <template #statusSlot="{ model, field }">
          <n-input v-model:value="model[field]" />
        </template>
      </BasicForm>
    </n-card>
    <n-card :bordered="false" class="tableCard">
      <BasicTable
        :bordered="false"
        :columns="columns"
        :request="viewList"
        :row-key="(row) => row.id"
        ref="actionRef"
        :actionColumn="actionColumn"
        :scroll-x="1090"
      >
        <template #tableTitle>
          <div
            style="
              border: 2px solid #2d8cf0;
              height: 32px;
              margin-right: 5px;
              background-color: #2d8cf0;
            "
          ></div>
          <p style="font-size: 15px">退款查询表格</p>
        </template>
      </BasicTable>
    </n-card>
    <!-- 查看 -->
    <n-modal v-model:show="viewShowModal">
      <n-card style="width: 430px" title="查看详情" :bordered="false" size="medium">
        <n-grid :cols="2">
          <n-gi style="margin-bottom: 10px">
            <n-form-item label="商品订单号：" label-placement="top">
              <n-input
                v-model:value="viewmodal.prodOrdNo"
                placeholder="暂无数据"
                style="width: 80%"
                readonly
                size="medium"
              />
            </n-form-item>
          </n-gi>
          <n-gi style="margin-bottom: 10px">
            <n-form-item label="原交易流水：" label-placement="top">
              <n-input
                v-model:value="viewmodal.prodOrdNo"
                placeholder="暂无数据"
                style="width: 80%"
                readonly
                size="medium"
              />
            </n-form-item>
          </n-gi>
          <n-gi style="margin-bottom: 10px">
            <n-form-item label="订单金额：" label-placement="top">
              <n-input
                v-model:value="viewmodal.payeeAmt"
                placeholder="暂无数据"
                style="width: 80%"
                readonly
                size="medium"
              />
            </n-form-item>
          </n-gi>
          <n-gi style="margin-bottom: 10px">
            <n-form-item label="会员号：" label-placement="top">
              <n-input
                v-model:value="viewmodal.memNo"
                placeholder="暂无数据"
                style="width: 80%"
                readonly
                size="medium"
              />
            </n-form-item>
          </n-gi>
          <n-gi style="margin-bottom: 10px">
            <n-form-item label="退款申请日期：" label-placement="top">
              <n-input
                v-model:value="viewmodal.applyDate"
                placeholder="暂无数据"
                style="width: 80%"
                readonly
                size="medium"
              />
            </n-form-item>
          </n-gi>
          <n-gi style="margin-bottom: 10px">
            <n-form-item label="退款金额：" label-placement="top">
              <n-input
                v-model:value="viewmodal.refundAmt"
                placeholder="暂无数据"
                style="width: 80%"
                readonly
                size="medium"
              />
            </n-form-item>
          </n-gi>
          <n-gi style="margin-bottom: 10px">
            <n-form-item label="退款比重：" label-placement="top">
              <n-input
                v-model:value="viewmodal.refundAmt"
                placeholder="暂无数据"
                style="width: 80%"
                readonly
                size="medium"
              />
            </n-form-item>
          </n-gi>
          <n-gi style="margin-bottom: 10px">
            <n-form-item label="退款状态：" label-placement="top">
              <n-space>
                <n-radio :checked="viewmodal.status === '0'" value="已退款" readonly>
                  已退款
                </n-radio>
                <n-radio :checked="viewmodal.status === '1'" value="未处理" readonly>
                  未处理
                </n-radio>
                <n-radio
                  :checked="viewmodal.status === '2'"
                  value="失败"
                  readonly
                  style="margin-right: 12px"
                >
                  失败
                </n-radio>
                <n-radio :checked="viewmodal.status === '3'" value="已拒绝" readonly>
                  已拒绝
                </n-radio>
              </n-space>
            </n-form-item>
          </n-gi>
          <n-gi style="margin-bottom: 10px">
            <n-form-item label="退款流水号：" label-placement="top">
              <n-input
                v-model:value="viewmodal.applicationNo"
                placeholder="暂无数据"
                style="width: 80%"
                readonly
                size="medium"
              />
            </n-form-item>
          </n-gi>
          <n-gi style="margin-bottom: 10px">
            <n-form-item label="退款失败原因：" label-placement="top">
              <n-input
                v-model:value="viewmodal.refuseReason"
                placeholder="暂无数据"
                style="width: 80%"
                readonly
                size="medium"
              />
            </n-form-item>
          </n-gi>
          <n-gi style="margin-bottom: 10px">
            <n-form-item label="会员备注：" label-placement="top">
              <n-input
                v-model:value="viewmodal.remark"
                placeholder="暂无数据"
                style="width: 80%"
                readonly
                size="medium"
              />
            </n-form-item>
          </n-gi>
        </n-grid>
        <template #action>
          <n-space justify="end">
            <n-button
              @click="() => (viewShowModal = false)"
              style="background-color: #2d8cf0; color: #fff"
              >确认</n-button
            >
          </n-space>
        </template>
      </n-card>
    </n-modal>
    <!-- 批准 -->
    <n-modal
      v-model:show="okModal"
      preset="dialog"
      title="确认"
      content="确认批准？"
      positive-text="确认"
      @positive-click="onPositiveClick"
      @negative-click="onNegativeClick"
      negative-text="取消"
    />
    <!-- 拒绝 -->
    <n-modal v-model:show="refuseModal">
      <n-card style="width: 600px" title="查看详情" :bordered="false" size="huge">
        <n-form-item label="拒绝原因" label-placement="left">
          <n-input
            v-model:value="refuseparm.refuseReason"
            placeholder="暂无数据"
            style="width: 80%"
            size="medium"
            type="textarea"
          />
        </n-form-item>
        <div style="height: 40px"> </div>
        <n-button @click="cancelRefuseClick" class="refuseButtonNo">取消</n-button>
        <n-button type="info" @click="onRefuseClick" class="refuseButton">确定</n-button>
      </n-card>
    </n-modal>
  </div>
</template>

<script lang="ts" setup>
import { h, reactive, ref, onMounted, defineAsyncComponent } from 'vue';
import { useMessage } from 'naive-ui';
import { BasicTable, TableAction } from '@/components/Table';
import { BasicForm, useForm } from '@/components/Formtrage/index';
import { getTableList } from '@/api/table/list';
import { columns } from './columns';
import { CreditCardOutlined } from '@vicons/antd';
import { useRouter } from 'vue-router';
import axios from 'axios';
import { refundapplyList } from '@/api/refundapply/list';
import { refundDetail } from '@/api/refundapply/detail';
import { refundApprove } from '@/api/refundapply/approve';
import components from '@/layout/components/Header/components';
import formatDate from '@/utils/timestamp';
import { createStorage } from '@/utils/Storage';
const Storage = createStorage({ storage: localStorage });

let authorityJson = Storage.get('OPERATORLIST');
const authority = JSON.parse(authorityJson);

function reloadTable() {
  csNumOne = -1;
  csNumTwo = -1;
  csNumThree = -1;
  actionRef.value.reload();
}

const handleSubmit = () => {
  reloadTable();
};
const handleReset = () => {
  parms.value.memNo = '';
  parms.value.status = '';
  parms.value.prodOrdNo = '';
  parms.value.payeeOrdNo = '';
  parms.value.startDate = '';
  parms.value.endDate = '';
  reloadTable();
};

const viewShowModal = ref(false);
const refuseModal = ref(false);
const okModal = ref(false);

const parms = ref({
  memNo: '',
  status: '',
  prodOrdNo: '',
  payeeOrdNo: '',
  startDate: '',
  endDate: '',
  pageNum: 1,
  pageSize: 10,
});
const jurisdiction = ref({});
const viewList = async (res) => {
  parms.value.pageNum = res.page;
  parms.value.pageSize = res.pageSize;
  let data = await refundapplyList(parms.value);
  jurisdiction.value = data.data.body.list;
  data.data.body.list.forEach((val) => {
    val.applyDate = formatDate(new Date(val.applyDate));
    if (val.status == '0') {
      val.status = '已退款';
    } else if (val.status == '1') {
      val.status = '未处理';
    } else if (val.status == '2') {
      val.status = '失败';
    } else if (val.status == '3') {
      val.status = '已拒绝';
    } else {
      val.status = '无法查看';
    }
  });
  let datas = {
    list: data.data.body.list,
    page: data.data.body.page,
    pageSize: data.data.body.pageSize,
    pageCount: Math.ceil(data.data.body.total / res.pageSize),
  };
  console.log(data);
  console.log(datas);
  console.log(jurisdiction.value);

  return datas;
};

const dealStatus = [
  {
    label: '全部状态',
    key: '全部状态',
  },
  {
    label: '已批准',
    key: '已批准',
  },
  {
    label: '已拒绝',
    key: '已拒绝',
  },
  {
    label: '未处理',
    key: '未处理',
  },
];

const schemas = [
  {
    field: 'startDate',
    component: 'NDatePicker',
    label: '申请日期：',
    componentProps: {
      type: 'daterange',
      clearable: true,
      onUpdateValue: (e: any) => {
        parms.value.startDate = e[0];
        parms.value.endDate = e[0];
      },
    },
  },
  {
    field: 'memNo',
    component: 'NInput',
    label: '会员号：',
    componentProps: {
      maxlength: 20,
      placeholder: '请输入会员号',
      onInput: (e: any) => {
        parms.value.memNo = e;
        console.log(e); // 交易会员姓名
      },
    },
  },
  {
    field: 'status',
    component: 'NSelect',
    label: '退款处理状态：',
    componentProps: {
      placeholder: '请选择',
      options: [
        {
          label: '全部',
          value: '',
        },
        {
          label: '已退款',
          value: 0,
        },
        {
          label: '未处理',
          value: 1,
        },
        {
          label: '失败',
          value: 2,
        },
        {
          label: '拒绝',
          value: 3,
        },
      ],
      onUpdateValue: (e: any) => {
        console.log(e);
        parms.value.status = e;
      },
    },
  },
  {
    field: 'prodOrdNo',
    component: 'NInput',
    label: '商品订单号：',
    componentProps: {
      maxlength: 20,
      placeholder: '请输入商品订单号',
      onInput: (e: any) => {
        parms.value.prodOrdNo = e;
        console.log(e); // 交易会员姓名
      },
    },
  },
  {
    field: 'payeeOrdNo',
    component: 'NInput',
    label: '原交易流水：',
    componentProps: {
      maxlength: 20,
      placeholder: '请输入原交易流水',
      onInput: (e: any) => {
        parms.value.payeeOrdNo = e;
        console.log(e); // 交易会员姓名
      },
    },
  },
];

const router = useRouter();
const formRef: any = ref(null);
const message = useMessage();
const actionRef = ref();

const showModal = ref(false);
const formBtnLoading = ref(false);
const formParams = reactive({
  name: '',
  address: '',
  date: null,
});

const params = ref({
  pageSize: 5,
  // name: 'xiaoMa',
});

const csButton = ref([
  {
    show: true,
  },
  {
    show: false,
  },
  {
    show: false,
  },
  {
    show: true,
  },
  {
    show: false,
  },
]);
let csNumOne = -1;
let csNumTwo = -1;
let csNumThree = -1;

// 列表行为
const actionColumn = reactive({
  width: 220,
  title: '操作',
  key: 'action',
  fixed: 'right',
  render(record) {
    return h(TableAction as any, {
      style: 'button',
      actions: [
        {
          label: '批准',
          text: true,
          color: '#2d8cf0',
          onClick: handleDelete.bind(null, record),
          ifShow: (val) => {
            csNumOne++;
            if (jurisdiction.value[csNumOne].status === '未处理') {
              return authority.includes('RefundApprove');
            } else {
              return false;
            }
          },
        },
        {
          label: '拒绝',
          text: true,
          color: '#ff4949',
          onClick: handleEdit.bind(null, record),
          ifShow: (val) => {
            csNumTwo++;
            if (jurisdiction.value[csNumTwo].status === '未处理') {
              return authority.includes('RefundApprove');
            } else {
              return false;
            }
          },
        },
        {
          label: '查看',
          text: true,
          color: '#2d8cf0',
          onClick: handleSee.bind(null, record),
          ifShow: (val) => {
            csNumThree++;
            if (jurisdiction.value[csNumThree].status !== '无法查看') {
              return authority.includes('RefundDetail');
            } else {
              return false;
            }
          },
        },
        // {
        //   label: '批准',
        //   icon: 'ic:CreditCardOutlined',
        //   color: '#2d8cf0',
        //   text: true,
        //   onClick: handleDelete.bind(null, record),
        // 根据业务控制是否显示 isShow 和 auth 是并且关系
        // ifShow: (val) => {
        //   csNumOne++
        //   console.log(csButton.value[csNumOne].show);
        //   return csButton.value[csNumOne].show;
        // },
        // 根据权限控制是否显示: 有权限，会显示，支持多个
        // auth: ['basic_list'],
        // },
        // {
        //   label: '拒绝',
        //   text: true,
        //   color: '#ff4949',
        //   onClick: handleEdit.bind(null, record),
        // ifShow: (val) => {
        //   csNumTwo++
        //   console.log(csButton.value[csNumTwo].show);
        //   return csButton.value[csNumTwo].show;
        // },
        // auth: ['basic_list'],
        // },
        // {
        //   label: '查看',
        //   text: true,
        //   color: '#2d8cf0',
        //   onClick: handleSee.bind(null, record),
        // ifShow: (val) => {
        //   csNumThree++
        //   console.log(csButton.value[csNumThree].show);
        //   return !csButton.value[csNumThree].show;
        // },
        // auth: ['basic_list'],
        // },
      ],
    });
  },
});

const [register, {}] = useForm({
  gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
  labelWidth: 80,
  schemas,
});

function addTable() {
  showModal.value = true;
}

const loadDataTable = async (res) => {
  return await getTableList({ ...res, ...formParams, ...params.value });
};

const refuseparm = ref({
  applicationNo: '',
  status: '2',
  refuseReason: '',
});

// 拒绝
function handleEdit(record: Recordable) {
  refuseparm.value.refuseReason = '';
  refuseModal.value = true;
  refuseparm.value.applicationNo = record.applicationNo;
}

const onRefuseClick = () => {
  refundApprove(refuseparm.value).then((val) => {
    if (val.data.sysHead.retCd == '000000') {
      message.success('已拒绝');
      refuseModal.value = false;
      reloadTable();
    }
  });
};

const cancelRefuseClick = () => {
  refuseModal.value = false;
  refuseparm.value.refuseReason = '';
};

const approveparm = ref({
  applicationNo: '',
  status: '1',
});

function handleDelete(record: Recordable) {
  okModal.value = true;
  approveparm.value.applicationNo = record.applicationNo;
  console.log('点击了批准', record);
}

const onNegativeClick = () => {
  okModal.value = false;
  message.info('取消批准');
};

const onPositiveClick = () => {
  okModal.value = false;
  refundApprove(approveparm.value).then((val) => {
    if (val.data.sysHead.retCd == '000000') {
      message.success('已批准');
      refuseModal.value = false;
      reloadTable();
    }
  });
};

const viewparm = ref({
  applicationNo: '',
});

const viewmodal = ref({
  applicationNo: '',
  applyDate: '',
  ccy: '',
  memNo: '',
  payeeAmt: '',
  payeeOrdNo: '',
  prodOrdNo: '',
  refundAmt: '',
  refundOrdNo: '',
  refuseReason: '',
  remark: '',
  seqNo: '',
  status: '',
});

const onViewClick = () => {
  viewShowModal.value = false;
};

function handleSee(record: Recordable) {
  viewShowModal.value = true;
  viewparm.value.applicationNo = record.applicationNo;
  refundDetail(viewparm.value).then((val) => {
    console.log(val.data.body);
    val.data.body.applyDate = formatDate(new Date(val.data.body.applyDate));
    viewmodal.value = val.data.body;
    console.log(viewmodal.value);
  });
  console.log('点击了查看', record);
}
</script>

<style lang="less" scoped>
.fromCard {
  margin-top: 12px;
  border: 1px solid rgb(226, 229, 229);
  margin-bottom: 8px;
}
.tableCard {
  border: 1px solid rgb(226, 229, 229);
}
.refuseButton {
  position: absolute;
  bottom: 20px;
  right: 30px;
}
.refuseButtonNo {
  position: absolute;
  bottom: 20px;
  right: 100px;
}
</style>
